package bingosoft.metro.code.service;

import java.util.ArrayList;
import java.util.List;

import bingosoft.components.base.service.BaseClass;
import bingosoft.metro.code.model.DbColumnModel;
import bingosoft.metro.code.model.DbTableModel;
import leap.db.model.DbColumn;
import leap.db.model.DbSchema;
import leap.db.model.DbTable;

/**
 * @author Feily
 * @功能描述 数据库服务接口默认类
 * @创建时间 2017-09-22
 */
public class DatabaseService extends BaseClass implements IDatabaseService {
	/**
	 * 构建函数
	 */
	public DatabaseService() {
		this.setLogClass(this.getClass());
	}
	
	@Override
	public DbTableModel getTable(String tableName){
		this.logMethodCalled("getTable");
		this.logParamValue("tableName", tableName);
		
		for (DbTableModel tableForm : this.queryAllTables()) {
			if(tableForm.getTableName().equalsIgnoreCase(tableName)){
				return tableForm;
			}
		}
		return null;
	}

	@Override
	public List<DbTableModel> queryAllTables(){
		this.logMethodCalled("queryAllTables");
		
		List<DbTableModel> list = new ArrayList<DbTableModel>();
		
		for (DbSchema schema : DbTableModel.dmo().getDbSchemas()) {
			for (DbTable table : schema.getTables()) {
				DbTableModel tableForm = new DbTableModel();
				tableForm.setTableName(table.getName());
				tableForm.setTableType(table.getType());
				tableForm.setTableComment(table.getComment());
				list.add(tableForm);
			}
		}
		
		return list;
	}
	
	@Override
	public List<DbColumnModel> queryColumns(String tableName){
		this.logMethodCalled("queryColumns");
		this.logParamValue("tableName", tableName);
		
		List<DbColumnModel> list = new ArrayList<DbColumnModel>();
	
		for (DbSchema schema : DbTableModel.dmo().getDbSchemas()) {
			for (DbTable table : schema.getTables()) {
				if(table.getName().equalsIgnoreCase(tableName)){
					for (int i = 0; i < table.getColumns().length; i++) {
						DbColumn column = table.getColumns()[i];
						
						DbColumnModel columnForm = new DbColumnModel();
						columnForm.setTableName(tableName);
						columnForm.setColumnId(i + 1);
						columnForm.setColumnName(column.getName());
						columnForm.setDataType(column.getTypeName());
						columnForm.setDataLength(column.getLength());
						columnForm.setDataPrecision(column.getPrecision());
						columnForm.setDataScale(column.getScale());
						columnForm.setNullable(column.isNullable());
						columnForm.setColumnComment(column.getComment());
						list.add(columnForm);
					}
				}
			}
		}
		return list;
	}
}
